package com.kobe.algorithm.leetcode.case1;

/**
 * @author ：caopengfei
 * @date ：2021/5/10
 */
public class Foo {

    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
    }

    public void second(Runnable printSecond) throws InterruptedException {

        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
    }

    public void third(Runnable printThird) throws InterruptedException {

        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }

     static  class PrintThread implements Runnable{

        private Object prev;
        private Object self;

        private String value;

        public PrintThread(Object prev, Object self, String value) {
            this.prev = prev;
            this.self = self;
            this.value = value;
        }

        @Override
        public void run() {
            //持有之前的锁
            synchronized (prev){
                synchronized (self){
                    System.out.print(this.value);
                    self.notifyAll();
                }
                try {
                    prev.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }

    public static void main(String[] args) throws Exception{

        Object lock1 = new Object();
        Object lock2 = new Object();
        Object lock3 = new Object();

        PrintThread first = new PrintThread(lock3,lock1,"first");
        PrintThread second = new PrintThread(lock1,lock2,"second");
        PrintThread third = new PrintThread(lock2,lock3,"third");

        Foo foo = new Foo();
        foo.first(first);
        foo.second(second);
        foo.third(third);

    }

}
